package com.zyb.patient.activity;

import java.io.File;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.View.OnClickListener;

import com.zyb.patient.R;
import com.zyb.patient.util.AboutImageTools;
import com.zyb.patient.util.LogUtil;
import com.zyb.patient.view.clip.ClipImageLayout;

public class AboutMeUserCenterClipActivity extends BaseActivity implements OnClickListener{
	
	private ClipImageLayout mClipImageLayout;
	private String path;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_usercenter_clipimage);
		path = getIntent().getStringExtra("path");
		if (TextUtils.isEmpty(path) || !(new File(path).exists())) {
			return;
		}
		
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		Bitmap bitmap = AboutImageTools.convertToBitmap(path, dm.widthPixels, dm.widthPixels);
		if (bitmap == null) {
			return;
		}
		mClipImageLayout = (ClipImageLayout) findViewById(R.id.id_clipImageLayout);
		mClipImageLayout.setBitmap(bitmap);
		
		(findViewById(R.id.id_action_clip)).setOnClickListener(this);
		(findViewById(R.id.id_action_cancle)).setOnClickListener(this);
	}
	
	@Override
	public void onClick(View view) {
		int id = view.getId();
		if(id == R.id.id_action_cancle){
			goCancle();
		}else if (id == R.id.id_action_clip){
			goClipBitmap();
		}
	}
	
	private void goCancle(){
		super.onBackPressed();
	}
	
	private void goClipBitmap(){
		new Thread(new Runnable() {
			@Override
			public void run() {
				long t1 = System.currentTimeMillis();
				Bitmap bitmap = mClipImageLayout.clip();
				long t2 = System.currentTimeMillis();
				LogUtil.e("time:" + (t2 - t1));
				long t3 = System.currentTimeMillis();
				String path = Environment
						.getExternalStorageDirectory()
						+ "/com.zyb.patient/cache/"
						+ System.currentTimeMillis() + ".jpg";
				AboutImageTools.savePhotoToSDCard(bitmap, path);
				long t4 = System.currentTimeMillis();
				LogUtil.e("time:" + (t4 - t3));
				if(bitmap != null){
					bitmap.recycle();
				}
				Intent intent = new Intent();
				intent.putExtra("path", path);
				setResult(RESULT_OK, intent);
				finish();
			}
		}).start();
	}
	
}
